<template>
  <div class="exams-page">
    <div class="page-header">
      <h1 class="page-title">我的考试</h1>
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索考试"
          prefix-icon="el-icon-search"
          @keyup.enter.native="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
    </div>

    <div class="filter-section">
      <div class="filter-group">
        <span class="filter-label">状态：</span>
        <el-radio-group v-model="filters.status" @change="handleFilterChange">
          <el-radio label="">全部</el-radio>
          <el-radio label="upcoming">即将开始</el-radio>
          <el-radio label="ongoing">进行中</el-radio>
          <el-radio label="completed">已完成</el-radio>
          <el-radio label="missed">已错过</el-radio>
        </el-radio-group>
      </div>
      <div class="filter-group">
        <span class="filter-label">学科：</span>
        <el-radio-group v-model="filters.subject" @change="handleFilterChange">
          <el-radio label="">全部</el-radio>
          <el-radio v-for="item in subjectOptions" :key="item.value" :label="item.value">
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </div>
    </div>

    <div class="exams-list">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="全部考试" name="all">
          <div v-if="examsList.length === 0" class="empty-state">
            <i class="el-icon-document"></i>
            <p>暂无考试</p>
          </div>
          <div v-else>
            <div v-for="(item, index) in examsList" :key="index" class="exam-card">
              <div class="exam-status" :class="getExamStatusClass(item.status)">
                {{ getExamStatusText(item.status) }}
              </div>
              <div class="exam-info">
                <h3 class="title">{{ item.title }}</h3>
                <p class="desc">{{ item.description }}</p>
                <div class="meta">
                  <div class="meta-item">
                    <i class="el-icon-date"></i>
                    <span>考试时间：{{ formatExamTime(item.startTime, item.endTime) }}</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-timer"></i>
                    <span>时长：{{ formatDuration(item.duration) }}</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-reading"></i>
                    <span>科目：{{ getSubjectText(item.subject) }}</span>
                  </div>
                  <div class="meta-item">
                    <i class="el-icon-notebook-2"></i>
                    <span>总分：{{ item.totalScore }}分</span>
                  </div>
                </div>
              </div>
              <div class="exam-actions">
                <template v-if="item.status === 'upcoming'">
                  <el-button type="info" @click="viewExamDetail(item)">查看详情</el-button>
                </template>
                <template v-else-if="item.status === 'ongoing'">
                  <el-button type="primary" @click="startExam(item)">开始考试</el-button>
                  <el-button type="info" @click="viewExamDetail(item)">查看详情</el-button>
                </template>
                <template v-else-if="item.status === 'completed'">
                  <el-button type="success" @click="viewExamResult(item)">查看成绩</el-button>
                  <el-button type="info" @click="viewExamDetail(item)">查看详情</el-button>
                </template>
                <template v-else>
                  <el-button type="info" @click="viewExamDetail(item)">查看详情</el-button>
                </template>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="错题集" name="wrongQuestions">
          <div v-if="wrongQuestionsList.length === 0" class="empty-state">
            <i class="el-icon-document"></i>
            <p>暂无错题</p>
          </div>
          <div v-else class="wrong-questions-list">
            <div v-for="(item, index) in wrongQuestionsList" :key="index" class="question-card">
              <div class="question-header">
                <span class="question-type">{{ getQuestionTypeText(item.type) }}</span>
                <span class="question-subject">{{ getSubjectText(item.subject) }}</span>
                <span class="question-exam">来自：{{ item.examTitle }}</span>
              </div>
              <div class="question-content">
                <div class="question-title" v-html="item.content"></div>
                <div class="question-options" v-if="['single', 'multiple'].includes(item.type)">
                  <div v-for="(option, idx) in item.options" :key="idx" class="option-item">
                    <span class="option-label">{{ String.fromCharCode(65 + idx) }}.</span>
                    <span class="option-content">{{ option.content }}</span>
                  </div>
                </div>
              </div>
              <div class="question-footer">
                <div class="answer-section">
                  <div class="your-answer">
                    <span class="label">你的答案：</span>
                    <span class="content wrong">{{ formatAnswer(item.userAnswer, item.type) }}</span>
                  </div>
                  <div class="correct-answer">
                    <span class="label">正确答案：</span>
                    <span class="content correct">{{ formatAnswer(item.correctAnswer, item.type) }}</span>
                  </div>
                </div>
                <div class="explanation" v-if="item.explanation">
                  <span class="label">解析：</span>
                  <span class="content">{{ item.explanation }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <div class="pagination-container" v-if="activeTab === 'all' && pagination.total > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="pagination.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
      ></el-pagination>
    </div>

    <div class="pagination-container" v-if="activeTab === 'wrongQuestions' && wrongQuestionsPagination.total > 0">
      <el-pagination
        @size-change="handleWrongQuestionsSizeChange"
        @current-change="handleWrongQuestionsCurrentChange"
        :current-page="wrongQuestionsPagination.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="wrongQuestionsPagination.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="wrongQuestionsPagination.total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import api from '@/api'

export default {
  name: 'ExamsList',
  data() {
    return {
      activeTab: 'all',
      searchQuery: '',
      filters: {
        status: '',
        subject: ''
      },
      subjectOptions: [
        { label: '语文', value: 'chinese' },
        { label: '数学', value: 'math' },
        { label: '英语', value: 'english' },
        { label: '物理', value: 'physics' },
        { label: '化学', value: 'chemistry' },
        { label: '生物', value: 'biology' },
        { label: '历史', value: 'history' },
        { label: '地理', value: 'geography' },
        { label: '政治', value: 'politics' }
      ],
      examsList: [],
      pagination: {
        page: 1,
        limit: 10,
        total: 0
      },
      wrongQuestionsList: [],
      wrongQuestionsPagination: {
        page: 1,
        limit: 10,
        total: 0
      }
    }
  },
  created() {
    this.fetchExams()
  },
  methods: {
    async fetchExams() {
      try {
        const params = {
          page: this.pagination.page,
          limit: this.pagination.limit,
          keyword: this.searchQuery,
          ...this.filters
        }
        
        const response = await api.exam.getExamList(params)
        this.examsList = response.data.items
        this.pagination.total = response.data.total
      } catch (error) {
        this.$message.error('获取考试列表失败')
        console.error('获取考试列表失败:', error)
      }
    },
    async fetchWrongQuestions() {
      try {
        const params = {
          page: this.wrongQuestionsPagination.page,
          limit: this.wrongQuestionsPagination.limit,
          keyword: this.searchQuery,
          subject: this.filters.subject
        }
        
        const response = await api.exam.getWrongQuestions(params)
        this.wrongQuestionsList = response.data.items
        this.wrongQuestionsPagination.total = response.data.total
      } catch (error) {
        this.$message.error('获取错题列表失败')
        console.error('获取错题列表失败:', error)
      }
    },
    handleTabClick(tab) {
      if (tab.name === 'wrongQuestions' && this.wrongQuestionsList.length === 0) {
        this.fetchWrongQuestions()
      }
    },
    handleSearch() {
      if (this.activeTab === 'all') {
        this.pagination.page = 1
        this.fetchExams()
      } else {
        this.wrongQuestionsPagination.page = 1
        this.fetchWrongQuestions()
      }
    },
    handleFilterChange() {
      if (this.activeTab === 'all') {
        this.pagination.page = 1
        this.fetchExams()
      } else {
        this.wrongQuestionsPagination.page = 1
        this.fetchWrongQuestions()
      }
    },
    handleSizeChange(val) {
      this.pagination.limit = val
      this.fetchExams()
    },
    handleCurrentChange(val) {
      this.pagination.page = val
      this.fetchExams()
    },
    handleWrongQuestionsSizeChange(val) {
      this.wrongQuestionsPagination.limit = val
      this.fetchWrongQuestions()
    },
    handleWrongQuestionsCurrentChange(val) {
      this.wrongQuestionsPagination.page = val
      this.fetchWrongQuestions()
    },
    getExamStatusClass(status) {
      const classMap = {
        upcoming: 'status-upcoming',
        ongoing: 'status-ongoing',
        completed: 'status-completed',
        missed: 'status-missed'
      }
      return classMap[status] || ''
    },
    getExamStatusText(status) {
      const textMap = {
        upcoming: '即将开始',
        ongoing: '进行中',
        completed: '已完成',
        missed: '已错过'
      }
      return textMap[status] || '未知状态'
    },
    getSubjectText(subject) {
      const subjectMap = {}
      this.subjectOptions.forEach(option => {
        subjectMap[option.value] = option.label
      })
      return subjectMap[subject] || '未知学科'
    },
    getQuestionTypeText(type) {
      const typeMap = {
        single: '单选题',
        multiple: '多选题',
        blank: '填空题',
        essay: '问答题'
      }
      return typeMap[type] || '未知类型'
    },
    formatExamTime(startTime, endTime) {
      if (!startTime) return '未设置'
      
      const start = new Date(startTime)
      const startStr = `${start.getFullYear()}-${String(start.getMonth() + 1).padStart(2, '0')}-${String(start.getDate()).padStart(2, '0')} ${String(start.getHours()).padStart(2, '0')}:${String(start.getMinutes()).padStart(2, '0')}`
      
      if (!endTime) return startStr
      
      const end = new Date(endTime)
      return `${startStr} 至 ${String(end.getHours()).padStart(2, '0')}:${String(end.getMinutes()).padStart(2, '0')}`
    },
    formatDuration(minutes) {
      if (!minutes) return '未设置'
      
      const hours = Math.floor(minutes / 60)
      const mins = minutes % 60
      
      if (hours > 0) {
        return `${hours}小时${mins > 0 ? ` ${mins}分钟` : ''}`
      }
      return `${mins}分钟`
    },
    formatAnswer(answer, type) {
      if (!answer) return '未作答'
      
      if (type === 'single') {
        return String.fromCharCode(65 + parseInt(answer))
      } else if (type === 'multiple') {
        return answer.split(',').map(item => String.fromCharCode(65 + parseInt(item))).join(', ')
      }
      return answer
    },
    viewExamDetail(exam) {
      this.$router.push(`/exam/${exam.id}`)
    },
    startExam(exam) {
      this.$router.push(`/exam/take/${exam.id}`)
    },
    viewExamResult(exam) {
      this.$router.push(`/exam/${exam.id}/result`)
    }
  }
}
</script>

<style lang="scss" scoped>
.exams-page {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .page-title {
      font-size: 24px;
      font-weight: bold;
      margin: 0;
    }
    
    .search-box {
      width: 300px;
    }
  }
  
  .filter-section {
    background-color: #f5f7fa;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 20px;
    
    .filter-group {
      margin-bottom: 10px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .filter-label {
        display: inline-block;
        width: 60px;
        font-weight: bold;
      }
    }
  }
  
  .exams-list {
    margin-bottom: 20px;
    
    .empty-state {
      text-align: center;
      padding: 40px 0;
      color: #909399;
      
      i {
        font-size: 48px;
        margin-bottom: 10px;
      }
      
      p {
        font-size: 16px;
        margin: 0;
      }
    }
    
    .exam-card {
      background-color: #fff;
      border-radius: 4px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      padding: 20px;
      margin-bottom: 20px;
      position: relative;
      
      .exam-status {
        position: absolute;
        top: 15px;
        right: 15px;
        padding: 2px 10px;
        border-radius: 12px;
        font-size: 12px;
        
        &.status-upcoming {
          background-color: #e6f7ff;
          color: #1890ff;
        }
        
        &.status-ongoing {
          background-color: #f6ffed;
          color: #52c41a;
        }
        
        &.status-completed {
          background-color: #f5f5f5;
          color: #8c8c8c;
        }
        
        &.status-missed {
          background-color: #fff2f0;
          color: #f5222d;
        }
      }
      
      .exam-info {
        margin-bottom: 20px;
        
        .title {
          font-size: 18px;
          margin: 0 0 10px;
          padding-right: 80px;
        }
        
        .desc {
          font-size: 14px;
          color: #606266;
          margin: 0 0 15px;
        }
        
        .meta {
          display: flex;
          flex-wrap: wrap;
          
          .meta-item {
            margin-right: 20px;
            margin-bottom: 10px;
            font-size: 14px;
            color: #606266;
            
            i {
              margin-right: 5px;
              color: #909399;
            }
          }
        }
      }
      
      .exam-actions {
        display: flex;
        justify-content: flex-end;
        
        .el-button {
          margin-left: 10px;
        }
      }
    }
    
    .wrong-questions-list {
      .question-card {
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        padding: 20px;
        margin-bottom: 20px;
        
        .question-header {
          display: flex;
          margin-bottom: 15px;
          
          .question-type,
          .question-subject,
          .question-exam {
            margin-right: 15px;
            font-size: 13px;
            padding: 2px 8px;
            border-radius: 3px;
          }
          
          .question-type {
            background-color: #ecf5ff;
            color: #409EFF;
          }
          
          .question-subject {
            background-color: #f0f9eb;
            color: #67c23a;
          }
          
          .question-exam {
            color: #606266;
          }
        }
        
        .question-content {
          margin-bottom: 15px;
          
          .question-title {
            font-size: 16px;
            margin-bottom: 10px;
            line-height: 1.6;
          }
          
          .question-options {
            padding-left: 20px;
            
            .option-item {
              margin-bottom: 8px;
              display: flex;
              
              .option-label {
                margin-right: 8px;
                font-weight: bold;
              }
              
              .option-content {
                flex: 1;
              }
            }
          }
        }
        
        .question-footer {
          border-top: 1px solid #ebeef5;
          padding-top: 15px;
          
          .answer-section {
            display: flex;
            margin-bottom: 10px;
            
            .your-answer,
            .correct-answer {
              margin-right: 20px;
              
              .label {
                font-weight: bold;
                margin-right: 5px;
              }
              
              .content {
                &.wrong {
                  color: #f56c6c;
                }
                
                &.correct {
                  color: #67c23a;
                }
              }
            }
          }
          
          .explanation {
            .label {
              font-weight: bold;
              margin-right: 5px;
            }
            
            .content {
              color: #606266;
            }
          }
        }
      }
    }
  }
  
  .pagination-container {
    text-align: center;
  }
}

@media (max-width: 768px) {
  .exams-page {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      
      .page-title {
        margin-bottom: 15px;
      }
      
      .search-box {
        width: 100%;
      }
    }
    
    .exams-list {
      .exam-card {
        .exam-info {
          .meta {
            flex-direction: column;
            
            .meta-item {
              margin-right: 0;
            }
          }
        }
        
        .exam-actions {
          flex-direction: column;
          
          .el-button {
            margin-left: 0;
            margin-bottom: 10px;
            
            &:last-child {
              margin-bottom: 0;
            }
          }
        }
      }
      
      .wrong-questions-list {
        .question-card {
          .question-header {
            flex-direction: column;
            
            .question-type,
            .question-subject,
            .question-exam {
              margin-right: 0;
              margin-bottom: 5px;
              display: inline-block;
            }
          }
          
          .question-footer {
            .answer-section {
              flex-direction: column;
              
              .your-answer,
              .correct-answer {
                margin-right: 0;
                margin-bottom: 10px;
              }
            }
          }
        }
      }
    }
  }
}
</style> 